package com.travelsky.flash.util.xml;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import com.travelsky.flash.util.log.FlashLogger;
import com.travelsky.flash.vo.SourceHostVO;

public class XMLObjUtil {
	
	private static FlashLogger logger = new FlashLogger(XMLObjUtil.class);
	
	private static JAXBContext jaxbContext = null;
	
	private static Marshaller marshaller = null;
	
	private static Unmarshaller unmarshaller = null;
	
	private static void initJaxbContext() {
		if(null == jaxbContext) {
			try {
				jaxbContext = JAXBContext.newInstance(SourceHostVO.class);
			} catch (JAXBException e) {
				logger.error(e);
			}
		}
	}
	
	private static void initMarshaller() {
		if(null == marshaller) {
			try {
				marshaller = jaxbContext.createMarshaller();
				marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
				marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			} catch (JAXBException e) {
				logger.error(e);
			}
		}
	}
	
	private static void initUnmarshaller() {
		if(null == unmarshaller) {
			try {
				unmarshaller = jaxbContext.createUnmarshaller();
			} catch (JAXBException e) {
				logger.error(e);
			}
		}
	}
	/**
	 * @Description 对象转xml文件
	 * @param filePath
	 * @param hostVO
	 * @author syuan
	 * @date 2015年7月16日  上午11:35:51
	 */
	public static void objToXmlFile(String filePath, SourceHostVO hostVO) {
		initJaxbContext();
		initMarshaller();
		File file = new File(filePath);
		try {
			marshaller.marshal(hostVO, file);
		} catch (JAXBException e) {
			logger.error(e);
		}
	}
	
	/**
	 * @Description xml文件转对象
	 * @param filePath
	 * @return
	 * @author syuan
	 * @date 2015年7月16日  下午12:15:10
	 */
	public static SourceHostVO xmlToObj(String filePath) {
		initJaxbContext();
		initUnmarshaller();
		File file = new File(filePath);
		try {
			return (SourceHostVO)unmarshaller.unmarshal(file);
		} catch (JAXBException e) {
			logger.error(e);
		}
		return null;
	}
}
